a<template>
  <div class="app-container">
    <el-form :inline="true" @submit.native.prevent>
      <el-form-item label="组织名称">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入组织名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="组织状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['system:dept:query']"
        >搜索
        </el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" v-hasPermi="['system:dept:export']"
                   @click="handleExport"
        >导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="deptName" label="组织名称" width="260"></el-table-column>
      <el-table-column prop="orderNum" label="排序" width="200"></el-table-column>
      <el-table-column prop="status" label="状态" :formatter="statusFormat" width="100"></el-table-column>
      <el-table-column prop="orgCode" label="组织编码" width="150"></el-table-column>

      <el-table-column label="logo" align="center" width="60">
        <!--        <template slot-scope="scope">-->
        <!--          <img :src="scope.row.logoUrl" alt="" style="width: 25px;height: 25px"/>-->
        <!--        </template>-->


        <template slot-scope="scope">
          <el-popover
            placement="right"
            trigger="hover"
          >
            <img :src="scope.row.logoUrl" style="width: 100px;height: 100px"/>
            <img slot="reference" :src="scope.row.logoUrl" style="width: 25px;height: 25px">
          </el-popover>
        </template>

      </el-table-column>

      <el-table-column prop="systemName" label="系统名称"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dept:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:dept:add']"
          >新增
          </el-button>
          <el-button
            v-if="scope.row.parentId !== 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dept:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :before-close="closeDialogConfirm">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <center>
              <div style="width: 50px;height: 50px;">
                <img :src="uploadLogoUrl" v-if="uploadLogoUrl" style="width: 50px;height: 50px">
              </div>
            </center>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <!-- 图片上传-->
            <center>
              <el-form-item label-width="0">
                <el-upload
                  ref="logoUpload"
                  accept=".jpg, .png"
                  :headers="upload.headers"
                  :action="upload.url"
                  :on-change="logoImageChange"
                  :disabled="upload.isLogoImgUploading"
                  :on-progress="handleLogoImgUploadProgress"
                  :on-success="handleLogoImgSuccess"
                  :auto-upload="false"
                  :show-file-list="false"
                  list-type="picture"
                >
                  <el-button size="small" style="margin-top: 5px;margin-bottom: 5px">选择logo</el-button>
                </el-upload>
              </el-form-item>
            </center>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级组织" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级组织"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="组织名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入组织名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织编码" prop="orgCode">
              <el-input v-model="form.orgCode" placeholder="请输入组织编码" :disabled="operationType==='modify'"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="系统名称" prop="systemName">
              <el-input v-model="form.systemName" placeholder="请输入系统名称"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addDept, delDept, exportDept, getDept, listDept, listDeptExcludeChild, updateDept } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getToken } from '@/utils/auth'

export default {
  name: 'Dept',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 表格树数据
      deptList: [],
      // 组织树选项
      deptOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 操作类型, add/modify, 修改时禁用组织编码
      operationType: '',
      // 组织结构树的根节点的parentId, 默认0
      rootDeptId: 0,
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: '上级组织不能为空', trigger: 'blur' }
        ],
        deptName: [
          { required: true, message: '组织名称不能为空', trigger: 'blur' }
        ],
        orgCode: [
          { required: true, message: '组织编码不能为空', trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: '菜单顺序不能为空', trigger: 'blur' }
        ],
        systemName: [
          { required: true, message: '系统名称不能为空', trigger: 'blur' }
        ],
        email: [
          {
            type: 'email',
            message: '\'请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ]
      },
      uploadLogoUrl: null,
      // 用户导入参数
      upload: {
        // 是否禁用上传
        isLogoImgUploading: false,

        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/image/uploadDeptLogoImage'
      },
      // logo图片对象
      logoImageObject: null,
      logoImageChanged: false,
      // logo图是否上传完成
      logoImageUploadCompleted: false,
      // 点击确定按钮后设置为true, 其余为false
      clickSubmit: false
    }
  },
  computed: {
    shouldSubmit() {
      if (this.clickSubmit) {
        // 若logo图片已修改, 则通过logoImageUploadCompleted判断是否需要提交
        if (this.logoImageChanged) {
          return this.logoImageUploadCompleted
        } else {
          return this.operationType === 'modify'
        }
      } else {
        return false
      }
    }
  },
  watch: {
    shouldSubmit(value) {
      // logo图片上传完成
      if (value) {
        this.submitAddOrUpdateDept()
      }
    }
  },
  created() {
    this.getList()
    this.getDictDataByType('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true
      listDept(this.queryParams).then(response => {
        const deptList = response.data
        // 获取根节点ID
        let parentIdList = []
        let rootId = 0
        // 遍历查询到的组织列表, 其中parentId最小的即是rootId
        for (let i = 0, len = deptList.length; i < len; i++) {
          parentIdList.push(deptList[i].parentId)
        }
        if (parentIdList.length > 0) {
          parentIdList.sort((a, b) => a - b)
          rootId = parentIdList[0]
        }
        this.rootDeptId = rootId

        this.deptList = this.handleTree(response.data, 'deptId', null, null, rootId)
        this.deptOptions = this.handleTree(response.data, 'deptId', null, null, rootId)
        // console.log(JSON.stringify(this.deptOptions))
        this.loading = false
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()

      this.open = false
      this.clickSubmit = false
      this.logoImageChanged = false
      this.logoImageUploadCompleted = false
      this.logoImageObject = null
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        logoUrl: '',
        systemName: undefined,
        orgCode: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: '0'
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      // 重新构建组织树结构
      this.uploadLogoUrl = null
      this.deptOptions = this.handleTree(this.deptList, 'deptId', null, null, this.rootDeptId)

      this.operationType = 'add'
      this.reset()
      this.open = true
      this.title = '添加组织'

      // 选中父级组织
      if (row !== undefined) {
        this.form.parentId = row.deptId
      }

      // 获取显示排序, 获取父节点的所有子节点, 得到子节点中的最大排序值, 然后加1
      if (this.form.parentId) {
        // 需要使用json重新解析
        let deptTree = JSON.parse(JSON.stringify(this.deptOptions))
        let orderNum = 1
        const parentNode = this.getNodeByDeptId(deptTree, this.form.parentId)
        // 若成功获取父节点
        if (parentNode) {
          const childrenNodes = parentNode.children
          // 若含有子节点
          if (childrenNodes && childrenNodes.length > 0) {
            // 遍历子节点, 获取最大排序值
            for (let i = 0, len = childrenNodes.length; i < len; i++) {
              if (orderNum < childrenNodes[i].orderNum) {
                orderNum = childrenNodes[i].orderNum
              }
            }
            orderNum++
          }
        }
        this.form.orderNum = orderNum
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.operationType = 'modify'
      this.uploadLogoUrl = row.logoUrl
      this.reset()
      getDept(row.deptId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改组织'
      })
      // 排除自己, 因为自己不能成为自己的父节点
      listDeptExcludeChild(row.deptId).then(response => {
        this.deptOptions = this.handleTree(response.data, 'deptId', null, null, this.rootDeptId)
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.clickSubmit = true
          // 上传图片
          this.$refs.logoUpload.submit()
        }
      })
    },

    submitAddOrUpdateDept() {
      if (this.logoImageObject) {
        this.form.logoUrl = this.logoImageObject.url
      }

      if (this.form.deptId !== undefined) {
        updateDept(this.form).then(response => {
          if (response.code === 200) {
            this.msgSuccess('修改成功')
          }
          this.open = false
          this.clickSubmit = false
          this.logoImageChanged = false
          this.logoImageUploadCompleted = false
          this.logoImageObject = null
          this.getList()
        })
      } else {
        addDept(this.form).then(response => {
          if (response.code === 200) {
            this.msgSuccess('新增成功')
          }
          this.open = false
          this.clickSubmit = false
          this.logoImageChanged = false
          this.logoImageUploadCompleted = false
          this.logoImageObject = null
          this.getList()
        })
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.deptName + '"的数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delDept(row.deptId)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    /**
     * 根据deptId获取组织结构树中的节点
     * @param tree 树形结构对象数组
     * @param deptId 需要查询的组织ID
     * @returns {*}
     */
    getNodeByDeptId(tree, deptId) {
      if (tree) {
        for (const node of tree) {
          if (node.deptId === deptId) return node

          if (node.children) {
            const selectedNode = this.getNodeByDeptId(node.children, deptId)
            if (selectedNode) return selectedNode
          }
        }
        return null
      }
      return null
    },

    // logo修改
    logoImageChange(file, fileList) {
      this.logoImageChanged = true
      this.uploadLogoUrl = file.url

      // 只保留最新的文件
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },

    // logo上传中处理
    handleLogoImgUploadProgress() {
      this.upload.isLogoImgUploading = true
    },

    // logo上传成功处理
    handleLogoImgSuccess(response) {
      this.logoImageObject = response.data
      this.$refs.logoUpload.clearFiles()
      this.upload.isLogoImgUploading = false
      this.logoImageUploadCompleted = true
    },

    /**
     * 对话框确认关闭
     */
    closeDialogConfirm() {
      this.$confirm('确认关闭?').then(() => {
        this.open = false
      }).catch(() => {
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return exportDept(this.queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    }
  }
}
</script>
